<?php
// 从环境变量获取数据库配置
$envFile = dirname(__DIR__) . '/.env';
$envConfig = parse_ini_file($envFile, true);

// 数据库配置
$hostname = $envConfig['DATABASE']['HOSTNAME'] ?? '127.0.0.1';
$database = $envConfig['DATABASE']['DATABASE'] ?? 'api_mh';
$username = $envConfig['DATABASE']['USERNAME'] ?? 'root';
$password = $envConfig['DATABASE']['PASSWORD'] ?? 'root';
$port = $envConfig['DATABASE']['HOSTPORT'] ?? 3306;

echo "==================================================\n";
echo "数据库导入工具\n";
echo "==================================================\n";
echo "正在连接到数据库...\n";

// 尝试连接数据库
try {
    $dsn = "mysql:host={$hostname};port={$port}";
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "数据库连接成功!\n";
    
    // 创建数据库（如果不存在）
    $sql = "CREATE DATABASE IF NOT EXISTS `{$database}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
    $pdo->exec($sql);
    echo "数据库 {$database} 已创建或已存在\n";
    
    // 选择数据库
    $pdo->exec("USE `{$database}`");
    echo "已选择数据库 {$database}\n";
    
    // 读取SQL文件
    $sqlFile = __DIR__ . '/create_database.sql';
    $sql = file_get_contents($sqlFile);
    
    echo "开始执行SQL脚本...\n";
    
    // 按语句分割SQL文件并执行
    $queries = explode(';', $sql);
    foreach ($queries as $query) {
        $query = trim($query);
        if (!empty($query)) {
            try {
                $pdo->exec($query);
                echo ".";
            } catch (PDOException $e) {
                echo "\n错误: " . $e->getMessage() . "\n";
            }
        }
    }
    
    echo "\n数据库结构已成功导入!\n";
    
} catch (PDOException $e) {
    echo "数据库连接或操作失败: " . $e->getMessage() . "\n";
    exit(1);
}

echo "==================================================\n";
echo "导入完成!\n";
echo "==================================================\n"; 